<template>
  <div>
    <div class="address_title">我的收货信息</div>
    <div class="order_info">
      <div class="info">{{ address_info }}</div>
      <div class="setinfo" @click="setAddress">立即设置</div>
    </div>

    <!-- 设置收货地址弹窗 -->
    <el-dialog
      title="设置收货地址"
      :visible.sync="showSetAddress"
      width="50%"
      @close="SetAddressClose"
      :close-on-click-modal="false"
    >
      <!-- 注册表单 -->
      <el-form
        ref="addressFormRef"
        :model="addressForm"
        :rules="addressFormRules"
        label-width="80px"
      >
        <!-- 收货人 -->
        <el-form-item prop="consignee" label="收货人">
          <el-input v-model="addressForm.consignee"></el-input>
        </el-form-item>
        <!-- 手机号 -->
        <el-form-item prop="address_phone" label="手机号">
          <el-input v-model="addressForm.address_phone"></el-input>
        </el-form-item>
        <!-- 邮编 -->
        <el-form-item prop="postcode" label="邮编">
          <el-input v-model="addressForm.postcode"></el-input>
        </el-form-item>
        <!-- 省市区 -->
        <el-form-item prop="province" label="省市区">
          <el-cascader
            size="large"
            :options="options"
            v-model="selectedOptions"
            :value="addressForm.province"
            @change="handleChange"
          >
          </el-cascader>
        </el-form-item>
        <!-- 详细地址 -->
        <el-form-item prop="address" label="详细地址">
          <el-input type="textarea" v-model="addressForm.address"></el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item class="btns">
          <el-button type="primary" @click="saveAddress">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { regionData, CodeToText } from 'element-china-area-data'
import { mapGetters } from 'vuex'
export default {
  data() {
    // 验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的手机号码'))
    }
    return {
      // 设置地址弹窗
      // 地址信息
      address_info: '',
      // 全部地址信息
      address: '',
      showSetAddress: false,
      addressForm: {},
      addressFormRules: {
        consignee: [
          { required: true, message: '请填写收货人姓名', trigger: 'blur' }
        ],
        address_phone: [
          { required: true, message: '请填写手机号', trigger: 'blur' },
          {
            validator: checkMobile,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        postcode: [{ required: true, message: '请填写邮编', trigger: 'blur' }],
        province: [
          { required: true, message: '请选择省市区', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请填写详细地址', trigger: 'blur' }
        ]
      },
      options: regionData,
      selectedOptions: []
    }
  },
  created() {
    this.getAddress()
  },
  methods: {
    // 打开弹窗
    setAddress() {
      console.log(this.address)
      if (this.address !== '') {
        this.addressForm = this.address
        this.selectedOptions = this.address.province.split(',')
      }
      this.showSetAddress = true
    },
    // 关闭弹窗
    SetAddressClose() {
      this.$refs.addressFormRef.resetFields()
    },

    // 获取收货地址
    async getAddress() {
      const { data: res } = await this.$http.get(
        '/address/getAddress' + '/' + this.getUser
      )
      if (res.code !== 200) return
      if (res.data[0] !== undefined) {
        console.log(res.data[0])
        this.address = res.data[0]
        let arr = this.address.province.split(',')
        let data =
          CodeToText[arr[0]] +
          ', ' +
          CodeToText[arr[1]] +
          ', ' +
          CodeToText[arr[2]]
        this.address_info =
          data.replaceAll(',', '') +
          ' ' +
          res.data[0].address +
          ' ' +
          res.data[0].postcode +
          ' (' +
          res.data[0].consignee +
          ' 收)' +
          ' ' +
          res.data[0].address_phone
      }
    },
    // 保存收货信息
    saveAddress() {
      this.$refs.addressFormRef.validate(async valid => {
        if (!valid) return
        // 如果已经有地址 则修改
        if (this.address !== '') {
          console.log(this.addressForm)
          const { data: updateRes } = await this.$http.put(
            '/address/updateAddress',
            {
              username: this.getUser,
              consignee: this.addressForm.consignee,
              address_phone: this.addressForm.address_phone,
              postcode: this.addressForm.postcode,
              province: this.selectedOptions.join(','),
              address: this.addressForm.address
            }
          )
          if (updateRes.code !== 200) return this.$message.error('保存地址失败')
          this.showSetAddress = false
          this.getAddress()
        } else {
          // 没有地址则添加
          const { data: addRes } = await this.$http.post(
            '/address/addAddress',
            {
              username: this.getUser,
              consignee: this.addressForm.consignee,
              address_phone: this.addressForm.address_phone,
              postcode: this.addressForm.postcode,
              province: this.selectedOptions.join(','),
              address: this.addressForm.address
            }
          )
          if (addRes.code !== 200) return this.$message.error('保存地址失败')
          this.$message.success('保存地址成功')
          this.showSetAddress = false
          this.getAddress()
        }
      })
    },
    // 省市区联动
    handleChange(value) {
      let data =
        CodeToText[value[0]] +
        ', ' +
        CodeToText[value[1]] +
        ', ' +
        CodeToText[value[2]]
      this.addressForm.province = data
      console.log(this.addressForm.province)
    }
  },
  computed: {
    ...mapGetters('user', ['getUser'])
  }
}
</script>

<style lang="scss" scoped>
.address_title {
  font-size: 24px;
  font-weight: bold;
  color: rgb(210, 172, 107);
  padding-bottom: 5px;
  margin-bottom: 5px;
  padding-left: 10px;
  border-bottom: 1px solid rgb(222, 222, 222);
}
.order_info {
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  color: #777;
  font-size: 12px;
  height: 20px;
  line-height: 20px;
  .setinfo {
    width: 65px;
    color: rgb(210, 172, 107);
    cursor: pointer;
  }
}
</style>
